//
//  LeftMenuTableViewController.m
//  UESTCPioneer
//
//  Created by Sway on 14-3-5.
//  Copyright (c) 2014年 Sway. All rights reserved.
//


#import "LeftMenuTableViewController.h"
#import "UPMenuTableViewCell.h"
#import "PioneerViewController.h"
#import "PartyNoticeViewController.h"
#import "PartyDataViewController.h"
#import "PartyActivityViewController.h"
#import "ServiceViewController.h"
#import "LeveyTabBarController.h"
#import "AppDelegate.h"
#import "helper.h"
#import "constant.h"


#import "RankViewController.h"


@interface LeftMenuTableViewController (){
    NSArray *unreadKeyArray;
    NSArray *nameArray ;
    NSArray *classArray;
    NSArray *cellIcon;
    NSArray *selectedCellIcon;
    UIColor *backGroundColor;
    UIColor *separatorColor;
    UIColor *newsCountLabelColor;
    UIColor *textColor;
    UIColor *selectedCellColor;
    NSIndexPath *indexForSelected;
    NSIndexPath *indexForHighlight;
    NSMutableArray *cellsIndex;
    BOOL thisIsJustOneTag;
}

@end

@implementation LeftMenuTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        
        separatorColor = [UIColor colorWithRed:119.0/255.0 green:123.0/255.0 blue:134.0/255.0 alpha:1];
        textColor = [UIColor colorWithRed:119.0/255.0 green:123.0/255.0 blue:134.0/255.0 alpha:1];
        newsCountLabelColor = [UIColor colorWithRed:119.0/255.0 green:123.0/255.0 blue:134.0/255.0 alpha:1];
        backGroundColor = [UIColor colorWithRed:37.0/255.0 green:41.0/255.0 blue:50.0/255 alpha:1];
        selectedCellColor = [UIColor colorWithRed:28.0/255.0 green:33.0/255.0 blue:39.0/255.0 alpha:1];
        cellsIndex = [[NSMutableArray alloc] initWithCapacity:5];
        self.tableView.rowHeight = 53;
        if(IS_IOS7)
            self.tableView.separatorInset = UIEdgeInsetsZero;
        self.tableView.backgroundColor = backGroundColor;
        self.tableView.separatorColor = separatorColor;
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    [self.tableView registerClass:[UPMenuTableViewCell class] forCellReuseIdentifier:@"settingCell"];
    [self setExtraCellLineHidden];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(displayNewsCount:) name:@"newsCount" object:nil];
    indexForSelected = [NSIndexPath indexPathForRow:0 inSection:0];
    nameArray=@[@"成电视角",@"党员活动",@"党员服务",@"通知公告",@"活跃排行"];
    classArray=@[[PioneerViewController class],[PartyActivityViewController class],[ServiceViewController class],[PartyNoticeViewController class],[RankViewController class]];
    cellIcon = @[@"news1.png",@"act1.png",@"service.png",@"notice1.png",@"rank1.png"];
    selectedCellIcon = @[@"news2.png",@"act2.png",@"service2.png",@"notice2.png",@"rank2.png"];
    
    unreadKeyArray=@[kUnreadPioneerKey,kUnreadPartyNoticeKey];
    
#pragma mark 未读信息读取
//    [self unreadRequest];

}

//set the selected cell style when enter from the remote notification
-(void)setCellStyleForRemote{
    NSIndexPath *notePath = [NSIndexPath indexPathForRow:3 inSection:0];
    UPMenuTableViewCell *cell = (UPMenuTableViewCell *)[self.tableView cellForRowAtIndexPath:notePath];
    cell.titleLabel.textColor = [UIColor whiteColor];
    cell.leftImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",selectedCellIcon[notePath.row]]];
    cell.contentView.backgroundColor = selectedCellColor;//set selected style
    
    if(indexForSelected.row != notePath.row){
        UPMenuTableViewCell *lastCell = (UPMenuTableViewCell *)[self.tableView cellForRowAtIndexPath:indexForSelected];
        lastCell.titleLabel.textColor = textColor;
        lastCell.leftImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",cellIcon[indexForSelected.row]]];
        lastCell.contentView.backgroundColor = backGroundColor;//set last cell back to unselected
    }
    
    indexForSelected = notePath;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if ([Unread getIsEnterFromRemote]) {
        NSLog(@"enter from notification");
        [self setCellStyleForRemote];
    }
    ((UPMenuTableViewCell *)[self.tableView cellForRowAtIndexPath:indexForSelected]).contentView.backgroundColor = selectedCellColor;
    [Unread setIsEnterFromRemote:NO];
    [self.tableView reloadData];
}

-(void)sendToNotificationCenter:(NSMutableArray *)newsCounts
{
    NSNotification *notification = [[NSNotification alloc] initWithName:@"newsCount" object:newsCounts userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
    //this place get newsCountLabel's presented number form cache or somewhere else
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"newsCount" object:nil];
}

-(void)displayNewsCount:(NSNotification *)notification
{
    if ([notification.object isKindOfClass:[NSMutableArray class]])
    {
        if ([[notification.object objectAtIndex:0] isKindOfClass:[NSString class]])
        {
            for (NSIndexPath *index in cellsIndex) {
                //[((UPMenuTableViewCell *)[self.tableView cellForRowAtIndexPath:index]) showNewsCountLabel:[[notification.object objectAtIndex:index.row] intValue]];
            }
        }
    }
}

#pragma mark - Table view data source

-(void)setExtraCellLineHidden
{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor clearColor];
    [self.tableView setTableFooterView:view];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [nameArray count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        
        return 67;
    }
    return 53;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"settingCell";
    UPMenuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    if (cell == nil) {
        cell = [[UPMenuTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.titleLabel.text=nameArray[indexPath.row];
    cell.leftImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",cellIcon[indexPath.row]]];
    
    //未读消息的显示
    if (indexPath.row == 3) {
        NSInteger unreadCount = [Unread getUnreadNumWithKey:kUnreadPartyNoticeKey];
        [cell showNewsCountLabel:unreadCount];
    }
    
    if(indexForSelected.row == indexPath.row){
        cell.leftImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",selectedCellIcon[indexPath.row]]];
        cell.titleLabel.textColor = [UIColor whiteColor];
    }
    
    if ([cellsIndex count] < 5) {
        [cellsIndex addObject:indexForSelected];
    }
    if(indexPath.row == 0){
        cell.leftImageView.frame = CGRectMake(16,25, 30, 30);
        cell.titleLabel.frame = CGRectMake(60, 15, 320, 53);
        cell.newsCountLabel.frame = CGRectMake(200, 32, 35, 20);
        
    }
    
    
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //点击消除未读消息
    if (indexPath.row == 3) {
        [Unread setUnreadNum:0 ForKey:kUnreadPartyNoticeKey];
    }
    if (indexPath.row == 1) {
        [constant setCurrentView:2];
    }else{
        [constant setCurrentView:0];
    }
    
    //界面切换
    Class theClass=classArray[indexPath.row];
    UIViewController *controller = [[theClass alloc] init];;
    
    [self.leveyTabBarController removeViewControllerAtIndex:0];
    [self.leveyTabBarController setSelectedIndex:1];
    
    [controller willMoveToParentViewController:self.leveyTabBarController];
    [self.leveyTabBarController insertViewController:controller  atIndex:0];
    [self.revealSideViewController popViewControllerWithNewCenterController:[constant getCenterController] animated:YES];
    [self.leveyTabBarController setSelectedIndex:0];
    [controller didMoveToParentViewController:[constant getCenterController]];
    ////////////////////////////////////////////
    
    UPMenuTableViewCell *cell = (UPMenuTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    cell.titleLabel.textColor = [UIColor whiteColor];
    cell.leftImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",selectedCellIcon[indexPath.row]]];
    cell.contentView.backgroundColor = selectedCellColor;//set selected style
    
    if(indexForSelected.row != indexPath.row){
        UPMenuTableViewCell *lastCell = (UPMenuTableViewCell *)[self.tableView cellForRowAtIndexPath:indexForSelected];
        lastCell.titleLabel.textColor = textColor;
        lastCell.leftImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",cellIcon[indexForSelected.row]]];
        lastCell.contentView.backgroundColor = backGroundColor;//set last cell back to unselected
    }
    
    [cell.newsCountLabel removeFromSuperview];
    indexForSelected = indexPath;
}

-(void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    UPMenuTableViewCell *cell = (UPMenuTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    cell.titleLabel.textColor = [UIColor whiteColor];
    cell.leftImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",selectedCellIcon[indexPath.row]]];
    indexForHighlight = indexPath;
}

-(void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexForHighlight.row != indexForSelected.row){
        UPMenuTableViewCell *cell = (UPMenuTableViewCell *)[self.tableView cellForRowAtIndexPath:indexForHighlight];
        cell.leftImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",cellIcon[indexForHighlight.row]]];
        cell.titleLabel.textColor = textColor;
    }//这里没有直接使用indexPath是因为在ios6下有bug，indexPath没有正确的指向相应的cell而是返回NSNotFound,不太明白这是怎么回事，所以通过indexForHighlight和indexForSelected绕过了参数indexPath
}


#pragma mark - unread Request
-(void)unreadRequest{
    //未读新闻
    /*
     type=getUnLookNews&userName=ping
     */
    
    NSDictionary *unreadNews =@{@"type":@"getUnLookNews"
                                ,@"userName":[constant getUserName]};
    
    [NetworkCenter AFRequestWithData:unreadNews SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil];
        NSString *num =dic[@"result"];
        
        [Unread setUnreadNum:[num integerValue] ForKey:kUnreadPioneerKey];
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    //未读党委通知
    /*
     type=unreadNotice&userId=0012005130022&userName=xiaopangzi
     */
    
    NSDictionary *unreadNotice = @{@"type":@"unreadNotice"
                                   ,@"userId":[constant getUserId]
                                   ,@"userName":[constant getUserName]};
    
    [NetworkCenter AFRequestWithData:unreadNotice SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil];
        NSString *num =dic[@"result"];
        [Unread setUnreadNum:[num integerValue] ForKey:kUnreadPartyNoticeKey];
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    //未读活动
    /*
     type=getUnLookEventCount&userNa
     
     */
    NSDictionary *unreadEvent = @{@"type":@"getUnLookEventCount"
                                  ,@"userId":[constant getUserId]
                                  ,@"userName":[constant getUserName]};
    
    [NetworkCenter AFRequestWithData:unreadEvent SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil];
        NSString *num =dic[@"result"];
        [Unread setUnreadNum:[num integerValue] ForKey:kUnreadPartyActivity];
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    //未读活动分享
    NSDictionary *unreadActivity = @{@"type":@"getUnLookShare"
                                     ,@"userId":[constant getUserId]
                                     ,@"userName":[constant getUserName]};
    
    [NetworkCenter AFRequestWithData:unreadActivity SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil];
        NSString *num =dic[@"result"];
        [Unread setUnreadNum:[num integerValue] ForKey:kUnreadMoodShare];
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
}

@end
